<?php
/**
 * Created by PhpStorm.
 * User: Shinelon
 * Date: 2021/4/17
 * Time: 15:24
 */

namespace app;


use app\admin\service\UpdateService;
use app\BaseController;
use think\App;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\View;
use think\Response;
use think\facade\Lang;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class IndexRest extends BaseController
{
    //app名称
    public $_app = null;
    //控制器名称
    public $_controller = null;
    //执行方法名称
    public $_action = null;
    //method
    public $_method = 'GET';
    //query参数
    public $_param = [];
    //body参数
    public $_input = [];
    //头部
    public $_header = [];
    public $_cookie = [];
    //头部token
    public $_token = null;
    //获取配置信息
    protected $_config = [];
    //语言信息
    public $_lang = 'zh-cn';
    //角色
    public $_role = 'guest';
    //host信息
    public $_host = null;
    //访问ip信息
    public $_ip = null;
    //用户信息
    public $_user = null;
    //唯一app标示
    public $_uniacid = '2';
    //定义检查中间件
//    protected $middleware = ['app\middleware\AppInit'];
//    protected $middleware = ['app\middleware\AppInit', 'app\middleware\CheckInput' ,'think\middleware\LoadLangPack' ,'app\middleware\AutoStatic','app\middleware\StaticHour', 'app\middleware\GetAuthConfig'];
    //判断是否是微擎
    public $_is_weiqin = false;
    /**
     * 小程序版本
     * 0 => 无限开版 其他 = 几开版
     * @var array
     */
    protected $card_auth_version = 0;
    protected $_admin = [];

    /**
     * 可开通名片数量
     * 0 => 无限开版 其他 = 名片数量
     * @var array
     */
    protected $card_auth_card = 0;

    public function __construct(App $app)
    {
        parent::__construct($app);
        //获取method
        $this->_method = $this->request->method(true);
//      if(in_array($this->_method,['options','Options','OPTIONS'])){
//          echo true;exit;
//      }


        //获取app名称
        $this->_app = $app->http->getName();
        //获取controller
        $this->_controller = $this->request->controller();
        //获取action名称
        $this->_action = $this->request->action();

        //获取param
        $this->_param = $this->request->param();
        //获取body参数
        $this->_input = json_decode($this->request->getInput(), true);
        //获取头部信息
        $this->_header = $this->request->header();
        $this->_cookie = $this->request->cookie();
        //获取访问ip
        $this->_ip = $_SERVER['REMOTE_ADDR'];
        $this->_token = $this->_cookie['token'] ?? '';
        $this->_admin = Cache::get($this->_token);
        View::assign(['admin' => $this->_admin]);
        $this->initialize();
    }

//返回请求成功的数据
    public function success($data, $code = 200)
    {
        $result = ['code' => $code, 'msg' => 'success', 'data' => [], 'sign' => null];
        if (is_array($data) || is_object($data))
            $result['data'] = $data;
        if (is_string($data))
            $result['msg'] = $data;
        //复杂的签名
        //        if(isset($this->_user['keys'])){
        //            $result['sign'] = rsa2CreateSign($this->_user['keys'] ,json_encode($data));
        //        }
        //简单的签名
        if (!empty($this->_token)) $result['sign'] = createSimpleSign($this->_token, is_string($data) ? $data : json_encode($data));
        return $this->response($result, 'json', $code);
    }

    //返回错误数据
    public function error($msg, $code = 400)
    {
        $result['error'] = Lang::get($msg);
        $result['code'] = $code;
        return $this->response($result, 'json', 200);
    }

    /**
     * 输出返回数据
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type 返回类型 JSON XML
     * @param integer $code HTTP状态码
     * @return Response
     */
    protected function response($data, $type = 'json', $code = 200)
    {
        return Response::create($data, $type)->code($code);
    }

    /**
     * REST 调用
     * @access public
     * @param string $method 方法名
     * @return mixed
     * @throws \Exception
     */
    public function _empty($method)
    {
        if (method_exists($this, $method . '_' . $this->method . '_' . $this->type)) {
            // RESTFul方法支持
            $fun = $method . '_' . $this->method . '_' . $this->type;
        } elseif ($this->method == $this->restDefaultMethod && method_exists($this, $method . '_' . $this->type)) {
            $fun = $method . '_' . $this->type;
        } elseif ($this->type == $this->restDefaultType && method_exists($this, $method . '_' . $this->method)) {
            $fun = $method . '_' . $this->method;
        }
        if (isset($fun)) {
            return App::invokeMethod([
                    $this,
                    $fun
                ]
            );
        } else {
            // 抛出异常
            throw new \Exception('error action :' . $method);
        }
    }

    /**
     * @Purpose: 获取formId
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */

    public function getFormId($to_uid)
    {
        return [];
        // 七天前开始的的时间戳
        // $beginTime = mktime( 0, 0, 0, date( 'm' ), date( 'd' ) - 6, date( 'Y' ) );
        $beginTime = strtotime(date('Y-m-d', time())) - 86400 * 6;
        $formId = Db::name('longbing_card_formId')
            ->where(['user_id' => $to_uid])
            ->order('id desc')
            ->select();
        if (empty($formId)) {
            return false;
        }
        if ($formId[0]['create_time'] < $beginTime) {
            Db::name('longbing_card_formId')
                ->where(['id' => $formId[0]['id']])
                ->delete();
            $this->getFormId($to_uid);
        } else {
            Db::name('longbing_card_formId')
                ->where(['id' => $formId[0]['id']])
                ->delete();
            return $formId[0]['formId'];
        }
    }

    /**
     *
     * 获取支付信息
     */
    public function payConfig()
    {
        $pay = Db::name('longbing_card_config_pay')->where(['uniacid' => $this->_uniacid])->find();
        $config = Db::name('longbing_card_config')->where(['uniacid' => $this->_uniacid])->find();
        if (empty($pay)) {
            $this->errorMsg('no config of pay');
        }
        $setting['payment']['merchant_id'] = $pay['mch_id'];
        $setting['payment']['key'] = $pay['pay_key'];
        $setting['payment']['cert_path'] = $pay['cert_path'];
        $setting['payment']['key_path'] = $pay['key_path'];
        $setting['app_id'] = $config['appid'];
        $setting['secret'] = $config['app_secret'];
        return $setting;
    }


    /**
     * User: chenniang
     * Date: 2019-09-12 20:37
     * @param string $msg
     * @return void
     * descption:直接抛出异常
     */
    protected function errorMsg($msg = '', $code = 400)
    {
        $msg = Lang::get($msg);
        $this->results($msg, $code);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为0
     * @param string $type 输出类型，支持json/xml/jsonp
     * @param array $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function results($msg, $code, array $header = [])
    {
        $result = [
            'error' => $msg,
            'code' => $code,
        ];
        $response = Response::create($result, 'json', 200)->header($header);
        throw new HttpResponseException($response);
    }

    public function https_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 60);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        } else {
            $result = curl_exec($curl);
        }
        curl_close($curl);
        return $result;
    }

    public function https_post($url, $data, $timeout = 30, $headers = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        // 关闭SSL验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        } else {
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data)
            ));
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function Datas($times, $day)
    {
        $data['today_start'] = strtotime(date("Y-m-d"), $times);//今日开始
        $data['today_end'] = $data['today_start'] + 60 * 60 * 24;//今日结束

        $data['day_start'] = $data['today_start'] - $day * 60 * 60 * 24;//昨日开始
        $data['day_end'] = $data['day_start'] + 60 * 60 * 24;//结束
        return $data;
    }

    public function MonthData($Month)
    {
        $month_start = strtotime($Month);//指定年月份月初时间戳
        $BeginDate = date('Y-m-01', strtotime($Month));
        $EndDate = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
        $month_end = strtotime("next day", strtotime($EndDate)) - 1;//指定年月份月末时间戳
        $data['day_start'] = $month_start;
        $data['day_end'] = $month_end;
        return $data;
    }

    function downloadExcel($newExcel, $filename, $format)
    {
        ob_end_clean();
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

        $objWriter->save('php://output');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
//         If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        exit;
    }

    public function getToken($admin)
    {
        $admin['time'] = time();
        $token = sha1($this->_ip . $admin['account'] . $admin['passwd'] . $admin['admin_id'] . $admin['time']);
        Log::info($token);
        Cache::set($token, $admin, 30 * 60);
        return $token;
    }
}